package com.gitee.vueantd.upload.rest;

import com.gitee.vueantd.common.annotation.AnonymousAccess;
import com.gitee.vueantd.common.utils.RedisUtils;
import com.gitee.vueantd.common.utils.download.BandWidthLimiter;
import com.gitee.vueantd.common.utils.download.HttpDownloadUtil;
import com.gitee.vueantd.system.security.config.bean.SecurityProperties;
import com.gitee.vueantd.upload.domain.UploadTaskData;
import com.gitee.vueantd.upload.repository.UploadTaskDataRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/download")
public class DownloadController {
  private final static int UNLIMITED = 1024 * 100000; // 100000M

  @Autowired
  private UploadTaskDataRepository uploadTaskDataRepository;
  @Autowired
  private SecurityProperties properties;
  @Autowired
  private RedisUtils redisUtils;

  @AnonymousAccess
  @GetMapping("/{fileId}")
  public void downloadPrivateFile(HttpServletRequest request,
                                  HttpServletResponse response,
                                  @PathVariable Long fileId,
                                  @RequestParam(value = "token") String token) {
    if (StringUtils.hasText(token) && redisUtils.hasKey(properties.getOnlineKey() + token.substring(7))) {
      Optional<UploadTaskData> optional = uploadTaskDataRepository.findById(fileId);
      if (optional.isPresent()) {
        String filePath = optional.get().getThumbnailPath();
        if (StringUtils.hasText(filePath)) {
          File file = FileUtils.getFile(filePath);
          if (file.exists() && file.isFile()) {
            try {
              HttpDownloadUtil.downloadFile(request, response, file, new BandWidthLimiter(UNLIMITED));
            } catch (Exception e) {
              log.error("{}", e);
            }
          } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            log.error("filePath doesn't exist {}", filePath);
          }
        }
      }


    } else {
      log.debug("error token = {}", token);
    }
  }

}
